package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.enums.OperatorType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.domain.BdmUser;
import com.ruoyi.system.domain.dto.BindUserDto;
import com.ruoyi.system.domain.vo.BdmMemberRuleVo;
import com.ruoyi.system.domain.vo.applet.AppletWxLoginVo;
import com.ruoyi.system.mapper.BdmMemberRuleMapper;
import com.ruoyi.system.service.IBdmUserService;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private BdmMemberRuleMapper bdmMemberRuleMapper;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IBdmUserService bdmUserService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 微信一键登录
     * @param appletWxLoginVo
     * @return
     */
    @PostMapping("/loginOpenid")
    public AjaxResult loginOpenid(@RequestBody AppletWxLoginVo appletWxLoginVo){
        return loginService.loginOpenid(appletWxLoginVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取省市区
     */
    @GetMapping("getChina")
    public AjaxResult getChina()
    {
        return AjaxResult.success(bdmMemberRuleMapper.getChina());
    }

    /**
     * 修改用户头像跟昵称
     * @param user
     * @return
     */
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody SysUser user)
    {
        user.setUserId(SecurityUtils.getUserId());
        return AjaxResult.success(iSysUserService.updateUserInfo(user));
    }

    /**
     * 获取微信用户信息
     *
     * @return 获取微信用户信息
     */
    @GetMapping("getWxUserInfo")
    public AjaxResult getWxUserInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser sysUser = iSysUserService.selectUserById(user.getUserId());
        user.setAvatar(sysUser.getAvatar());
        user.setNickName(sysUser.getNickName());
        BdmUser bdmUser = bdmUserService.lambdaQuery().eq(BdmUser::getSysUserid, user.getUserId()).one();
        user.setRemainingSum(bdmUser.getRemainingSum());
        user.setEarnings(bdmUser.getEarnings());
        user.setCreditScore(bdmUser.getCreditScore());
        user.setPayPassword(StringUtils.isEmpty(bdmUser.getPayCode())?1:2);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        SysUser parentUser = iSysUserService.selectUserById(bdmUser.getParentId());
        if (ObjectUtils.isNotEmpty(parentUser)){
            bdmUser.setParentNickName(parentUser.getNickName());
        }
        ajax.put("bdmUser",bdmUser);
        BdmMemberRuleVo bdmMemberRuleVo = bdmMemberRuleMapper.selectMemberRuleByUserId(user.getUserId());
        if (bdmMemberRuleVo == null) {
            bdmMemberRuleVo = new BdmMemberRuleVo();
            bdmMemberRuleVo.setMemberLevel(0L);
            bdmMemberRuleVo.setMemberAgencyLevel(0L);
        }else if (StringUtils.isBlank(bdmMemberRuleVo.getMemberAgencyLevelName())){
            bdmMemberRuleVo.setMemberAgencyLevelName(":暂未获得身份");
        }
        ajax.put("memberUserInfo", bdmMemberRuleVo);
        return ajax;
    }

    /**
     * 绑定上下级关系
     * @return
     */
    @PostMapping("/binding")
    @Log(title = "扫码绑定关系", businessType = BusinessType.EXPORT, operatorType = OperatorType.MOBILE)
    public AjaxResult binding(@RequestBody AppletWxLoginVo appletWxLoginVo)
    {
        BindUserDto bindUserDto =new BindUserDto();
        bindUserDto.setCodeUserId(appletWxLoginVo.getPromotionId());
        bindUserDto.setScanUserId(SecurityUtils.getUserId());
        bdmUserService.bindUser(bindUserDto);
       // iSysUserService.binding(appletWxLoginVo);
        return AjaxResult.success();
    }
}
